<?
session_start();
$vcpserver="sms.todaynic.com"; 
$vcpserverport="20002"; 
$vcpuser="ms117"; 
$vcppassword="kswidt"; 
$newclient=new SMS();
if($newclient->ConfNull=="1"){
	$mobile = $_POST[PhoneNum];
	$message = $_POST[Msg];
	$time = $_POST[dtTime];
	$apitype = $_POST[apitype];; // $apitype 通道选择 0：默认通道； 2：通道2； 3：即时通道；
	$respxml=$newclient->sendSMS($mobile, $message, $time, $apitype);
	
	//print_r($newclient->sendXML);die();
	
	$_SESSION["xml"]=$newclient->sendXML;
	$_SESSION["respxml"]=$respxml;
	$code=$newclient->getCode();
	$respArr=$newclient->toArray();
	$mess=$respArr["msg"];
	$smsid=$respArr["idmessage"][0];
	$succnum=$respArr["successnum"][0];
	$succphone=$respArr["successphone"][0];
	$failephone=$respArr["failephone"][0];
}
else {
	$code = "<font color='red'>失败</font>";
	$ermess = "<font color='red'>配置错误</font>";
	$error = "<font color='red'>失败</font>";
}

class SMS extends XMLClient
{
	var $ConfNull="1";
	function SMS()
	{
		//if(file_exists("api/config.inc.php"))
		//	include "api/config.inc.php"; //请填写你放置config.inc.php文件的路径,这是配置文件
		//else $this->ConfNull = "-1";
		$this->serverURL=$vcpserver.":".$vcpserverport;
		$this->XMLType="SMS";
		$this->VCP=$vcpuser;
		$this->VCPPassword=$vcppassword;
	}
	//发送SMS短信接口
	function sendSMS($mobile, $msg, $time="", $apitype=0)
	{
		$xml_command="<action>SMS:sendSMS</action>
						<sms:mobile>$mobile</sms:mobile>
						<sms:message>".base64_encode($msg)."</sms:message>
						<sms:datetime>$time</sms:datetime>
						<sms:apitype>$apitype</sms:apitype>";
		$this->sendSCPData($this->serverURL, $xml_command);
		$this->toPlain();
		return $this->responseXML;
	}
	//查询远程账户余额
	function infoSMSAccount()
	{
		$xml_command="<action>SMS:infoSMSAccount</action>";
		$this->sendSCPData($this->serverURL, $xml_command);
		$this->toPlain();
		return $this->responseXML;
	}
	//接收SMS短信接口
	function readSMS()
	{
		$xml_command="<action>SMS:readSMS</action>";
		$this->sendSCPData($this->serverURL, $xml_command);
		$this->toPlain();
		return $this->responseXML;
	}
	function updateConf($username, $pass, $server){
		if(!file_exists("api/config.inc.php")) return "文件smsdemo/api/config.inc.php 不存在！";
		if(!is_writable("api/config.inc.php")) return "文件smsdemo/api/config.inc.php 不可写！请检查文件属性！";
		$fd = fopen("api/config.inc.php","w");
		if(!$fd) return "文件smsdemo/api/config.inc.php 打不开, 请检查文件属性！";
		$line = '<? '."\n".
				'/** '."\n".
				' * 这是配置文件 '.
				' * $'."vcpserver		SCP服务器地址，测试服务器为testxml.todaynic.com，正式服务器为sms.todaynic.com "."\n".
				' * $'."vcpserverport	SCP服务器，在测试环境和真实环境，使用的接口均为20002 "."\n".
				' * $'."vcpsuser		时代互联提供的真实短信用户或测试用户 "."\n".
				' * $'."vcppassword		 时代互联提供的真实短信用户密码或测试用户密码 "."\n".
				' * '."\n".
				' * www.now.cn,Inc. http://www.now.cn '."\n".
				'**/ '."\n".
				'$'.'vcpserver="'.$server.'"; '."\n".
				'$'.'vcpserverport="20002"; '."\n".
				'$'.'vcpuser="'.$username.'"; '."\n".
				'$'.'vcppassword="'.$pass.'"; '."\n".
				'?> '."\n";
		if(fwrite($fd, $line)===FALSE) return "文件smsdemo/api/config.inc.php 写入失败！请检查文件属性！";
		fclose($fd);
		return "1";
	}
}

class XMLClient
{
	var $responseXML;
	var $sendXML;
	var $DEBUG=0;
	var $serverURL;
	var $XMLType;
	var $VCP;
	var $VCPPassword;
	function getCode()
	{
		$start_pos = strpos($this->responseXML, "<result code=\"");
		return trim(substr($this->responseXML, $start_pos + 14, 4));
	}
	function getMessage()
	{
		return getValue("msg",$this->responseXML);
	}
	function isSuccess()
	{
		return eregi("successfully",$this->responseXML);
	}
	function sendXMLData($XMLDATA)
	{
			$this->sendXML=$XMLDATA;
			$buffer=8192;	//设置缓冲大小
			$timeout=20;	//设置socket连接超时时间
			$this->responseXML="";
			if($this->DEBUG)echo "sendxml:".$XMLDATA;
			$this->serverURL=eregi_replace("^http://","",$this->serverURL);
			$pos=strpos($this->serverURL,"/");
			if($pos>0){
				$deshost=substr($this->serverURL,0,$pos);
				$despath=substr($this->serverURL,$pos);
			}else{
				$deshost=$this->serverURL;
				$despath="/";
			}
			$pos=strpos($deshost,":");
			if($pos>0){
				$port=substr($deshost,$pos+1);
				$deshost=substr($deshost,0,$pos);
			}else $port=80;
			if($this->DEBUG) echo "$deshost:$port:$despath";
			if(strlen($deshost)==0 || strlen($despath)==0 || $port<=0)
			{
				$this->responseXML="HOST:".$deshost."   PORT:".$port."   PATH:".$despath;
				return $this->responseXML;
			}
			$fp =@fsockopen($deshost, $port, $errno, $errstr, $timeout);
			if(!$fp)
			{
				$this->responseXML="unable to connect to ".$deshost.":".$port;
				return $this->responseXML;
			}
			/*
			$out = "POST $despath HTTP/1.1\r\n";
			$out .= "Host: $deshost\r\n";
			$out .= "Content-Length: ".strlen($XMLDATA)."\r\n";
			$out .= "Connection: Close\r\n\r\n";
			*/
			$out=$XMLDATA;
			fputs($fp, $out);
			do {
				$data = fread($fp, $buffer);
				if (strlen($data) == 0) break;
				$contents = $data;
				if (eregi("</scp>", $contents)) break;
			} while(true);
			fclose($fp);
			$this->responseXML=$contents;
			if($this->DEBUG) echo $this->responseXML;
			if(!$this->responseXML) $this->responseXML="NO XML Error,please check the xml which post to Server.";
			return $this->responseXML;
	}
    function toPlain(){
		$contents=trim($this->responseXML);
		$contents=strstr($contents,"<?xml");
		$end=strpos($contents,"</scp>")+strlen("</scp>");
		$contents=substr($contents,0,$end);
		if($contents)	$this->responseXML=$contents;
		return $this->responseXML;
	}
	function sendSCPData($desurl,$XMLDATA){
		 $XMLDATA=$this->toSCPXML($XMLDATA);
         return $this->sendXMLData($XMLDATA);
	}
	function toArray($content="response",$parsetype=0){
		$parser = xml_parser_create();
		xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
		xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
		xml_parse_into_struct($parser,$this->responseXML,$values,$tags);
		xml_parser_free($parser);
		$showMess=XMLtoArray($values,$tags,$content,$parsetype);
		if(!$showMess)	$showMess[Error]=$this->responseXML;
		return $showMess;
	}
	function toSCPXML($CommandXML)
	{
		$cltrid=CltrID();
		$clientid=getENCID($cltrid,$this->VCPPassword);
		$xmlns = $this->getXMLNS();
		$secruser = $this->getSecurityUser();
		$respxml="<?xml version=\"1.0\" encoding=\"GB2312\"?>
		<scp $xmlns>
			<command>
				   $CommandXML
			</command>
			<security>
				$secruser
				<cltrid>$cltrid</cltrid>
				<login>$clientid</login>
		   </security>
		</scp>";
		//格式化XML,以便显示时好看一点
        //$respxml=eregi_replace("\t","    ",$respxml);
		return $respxml;
	}
	function getXMLNS()
	{
		if(strtoupper($this->XMLType)=="SMS"){
			$xmlns = "xmlns=\"urn:mobile:params:xml:ns:scp-1.0\"
			  xmlns:sms=\"urn:todaynic.com:sms\"
			  xmlns:user=\"urn:todaynic.com:user\"";
		}
		else $xmlns = "xmlns=\"urn:scp:params:xml:ns:scp-3.01\"
			  xmlns:host=\"urn:todayisp.com:client\"";
		return $xmlns;
	}
	function getSecurityUser()
	{
		if(strtoupper($this->XMLType)=="SMS"){
			$secruser = "<smsuser>$this->VCP</smsuser>";
		}
		else $secruser = "<vcpuser>$this->VCP</vcpuser>";
		return $secruser;
	}
	function getUserInfo($contactI)
	{
		$sendxml="<action>user:detail</action>
					<userid>$contactI[userid]</userid>
					<userpassword>$contactI[userpassword]</userpassword>";
		$this->sendSCPData($this->serverURL,$sendxml);
		$this->toPlain();
		return $this->responseXML;
	}
}

function CltrID()
{
	list($usec, $sec) = explode(" ",microtime());
	$cltrid=$usec*100 + $sec*100;
	return round($cltrid);
}
function getENCID($cltrid,$password)
{
	return md5("$cltrid-$password");
}
function getValue($value,$CutXml)
{
		//if(!$CutXml)$CutXml=$this->responseXML;
		$key = $value;
		if (strpos($value, "-")) $value = substr($value, 0, strpos($value, "-"));
		$str1 = "<".$value;
		$str2 = "</".$value;
		$start_pos = strpos($CutXml, $str1);
		if ($start_pos > 0){
			$start_pos += strlen($str1);
			$CutXml = substr($CutXml, $start_pos);
			$end_pos = strpos($CutXml, $str2);
			$resValue = substr($CutXml, strpos($CutXml,">")+1, $end_pos-strpos($CutXml,">")-1);
		}
		return $resValue;
}
function parseMol($mvalues,$mretype=0)
{
	if($mvalues[0]["type"]=="open")
	{
		for ($i=1; $i < count($mvalues); $i++)
		{
			$key=$mvalues[$i]["tag"];
			if(!$mretype)$mol[$key][] = $mvalues[$i]["value"];
			else{
				$arr["value"] = $mvalues[$i]["value"];
				if(isset($mvalues[$i]["attributes"]))
					$arr["attributes"] = $mvalues[$i]["attributes"];
				$mol[$key][] = $arr;
			}
		}
	}
	return $mol;
}
function XMLtoArray($values,$tags,$item,$parsetype=0)
{
	foreach ($tags as $key=>$val)
	{
		if($key == $item)
		{
			$molranges = $val;
			$offset = $molranges[0];
			$len = $molranges[1] - $offset;
			$data=parseMol(array_slice($values, $offset, $len),$parsetype);
		 }
	}
	return $data;
}
function XMLgetValue($values,$tags,$item)
{
		foreach ($tags as $key=>$molranges)
		{
			if($key == $item)
			{
				for($i=0;$i<$num;$i++)
				$data[]=$values[$molranges[$i]]["value"];
			}
		}
		return $data;
}
function toArray($xml,$content="response"){
	$parser = xml_parser_create();
	xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
	xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
	xml_parse_into_struct($parser,$xml,$values,$tags);
	xml_parser_free($parser);
	$dbxml=XMLtoArray($values,$tags,$content);
	return $dbxml;
}
?>